package main

import (
	"github.com/astaxie/beego/orm"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"net/http"
	"os"
	"strings"
	"talentsystem/service"
	"talentsystem/model"
	"time"
	"github.com/gin-gonic/contrib/sessions"
)

type Rounters struct {
	Path    string
	Handler gin.HandlerFunc
}

func options(c *gin.Context) {
	c.JSON(200, gin.H{
		"status": 200,
	})
}

func main() {
	registerDB()
	rounter := gin.Default()
	store := sessions.NewCookieStore([]byte("secret"))
	store.Options(sessions.Options{
		MaxAge: int(60*time.Minute), //session 存在1小时
	})
	apis := []Rounters{
		{"/test",service.Test},
		{"/httpgetusermsg",service.HttpGetUserMsg},
		{"/httpget",service.HttpGet},
		{"/getaccountapplyjob",service.GetAccountApplyJob},
		{"/getoneaccountapplyjob",service.GetOneAccountApplyJob},
		{"/updateaccountapplyjob",service.UpdateAccountApplyJob},
		{"/insertaccountapplyjob",service.InsertAccountApplyJob},
		{"/getaccountheadhunters",service.GetAccountHeadhunters},
		{"/getoneaccountheadhunters",service.GetOneAccountHeadhunters},
		{"/updateaccountheadhunters",service.UpdateAccountHeadhunters},
		{"/insertaccountheadhunters",service.InsertAccountHeadhunters},
		{"/getposition",service.GetPosition},
		{"/getoneposition",service.GetOnePosition},
		{"/updateposition",service.UpdatePosition},
		{"/insertposition",service.InsertPosition},
		{"/obtainaliyunsmsauthcode",service.ObtainAliyunSmsAuthCode},
		{"/loginaccount",service.LoginAccount},
		{"/uploadaccountmsg",service.UploadAccountMsg},
		{"/uploadimg",service.UploadImg},
		{"/forgetpwd",service.ForgetPwd},
		{"/updatepwd",service.UpdatePwd},
		{"/deliverresume",service.DeliverResume},
		{"/perfectyourresume",service.PerfectYourResume},
		{"/updateyourresume",service.UpdateYourResume},
		{"/updateyourresumehope",service.UpdateYourResumeHope},
		{"/updateyourresumeexperence",service.UpdateYourResumeExperence},
		{"/updateyourresumeeducation",service.UpdateYourResumeEducation},
		{"/updateyourresumeability",service.UpdateYourResumeAbility},
		{"/perfectenrol",service.PerfectEnrol},
		{"/updaternrol",service.UpdateErnrol},
		{"/enrollog",service.EnrolLog},
		{"/getresumelog",service.GetResumeLog},
		{"/updateuesumelogstatus",service.UpdateResumeLogStatus},
		{"/getaajresumelog",service.GetAAJResumeLog},
		{"/getenrollog",service.GetEnrolLog},
		{"/updateenrollogstatus",service.UpdateEnrolLogStatus},
		{"/getahhenrollog",service.GetAccountHeadhuntersEnrolLog},
		{"/insertgrade",service.InsertGrade},
		{"/ahhgrade",service.AHHGrade},
		{"/addcommission",service.AddCommission},
		{"/requestwithdrawal",service.RequestWithdrawal},
		{"/getahhmoney",service.GetAHHMoney},
		{"/getrecordlog",service.GetRecordLog},
		{"/getallrecordlog",service.GetAllRecordLog},
		{"/updaterecordlog",service.UpdateRecordLog},
		{"/feedback",service.Feedback},
		{"/getfeedback",service.GetFeedback},
		{"/systemlogin",service.SystemLogin},
		{"/insertadmin",service.InsertAdmin},
		{"/haveresume",service.HaveResume},
		{"/delposition",service.DelPosition},
		{"/gettransfer",service.Gettransfer},
		{"/updatetranfer",service.UpdateTranfer},
		{"/inserttranfer",service.InsertTranfer},
	}
	api := rounter.Group("/api")
	api.Use(AccessJsMiddleware())
	{
		for _, v := range apis {
			api.OPTIONS(v.Path, options)
			api.POST(v.Path, v.Handler)
		}
	}
	/*rounter.Use(Handle404NotFound)*/
	rounter.Static("/", "./static")
	rounter.Run(":11250")
}
//获取登录状态
/*func GetSession(c*gin.Context)  {
	url := c.Request.URL.String()
	if url!="/api/systemlogin"{
		session := sessions.Default(c)
		v := session.Get("admin")
		if v!=1{
			http.Redirect(c.Writer, c.Request, "/index.html", 302)
			c.Abort()
		}else{
			c.Next()
		}
	}
}*/
func Handle404NotFound(c *gin.Context) {
	url := c.Request.URL.String()
	if len(url) > 4 && string([]byte(url)[:5]) != "/api/" {
		var path string = url
		paths := strings.Split(url, "?")
		if len(paths) > 1 {
			path = paths[0]
		}
		if exist, err := PathExists("static" + path); err != nil {
			c.AbortWithError(500, err)
		} else if !exist {
			http.Redirect(c.Writer, c.Request, "/404page.html", 302)
			c.Abort()
		}
	}
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
func AccessJsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		w := c.Writer
		// 处理js-ajax跨域问题
		w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
		w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, POST")
		w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
		w.Header().Add("Access-Control-Allow-Headers", "Access-Token")
		c.Next()
	}
}

//连接数据库
func registerDB() {
	orm.Debug = true
	orm.RegisterDataBase("default", "mysql", "root:123456@/talentsystem?charset=utf8", max_idle, max_open)
	orm.RegisterModel(
		new(model.AccountApplyJob),
		new(model.AccountHeadhunters),
		new(model.Resume),
		new(model.ResumeAbility),
		new(model.ResumeEducation),
		new(model.ResumeExperence),
		new(model.ResumeHope),
		new(model.Position),
		new(model.ResumeLog),
		new(model.Enrol),
		new(model.EnrolLog),
		new(model.Grade),
		new(model.RecordLog),
		new(model.Feedback),
		new(model.Admin),
		new(model.Transfer),
	)
	orm.RunSyncdb("default", false, true)
}

//最大连接数和最大等待连接数
const (
	max_idle = 20000
	max_open = 9000
)